#!/bin/bash
root_dir="/usr/local/edata"
if [ ! -d "$root_dir" ];then
  echo "$(date +"%Y-%m-%d %H:%M:%S") WARNING $root_dir undetected"
  mkdir -p $root_dir
  if [ $? -eq 0 ];then
    echo "$(date +"%Y-%m-%d %H:%M:%S") INFO creating $root_dir success"
  else
    echo "$(date +"%Y-%m-%d %H:%M:%S") ERROR creating $root_dir fail"
    exit 1
  fi
else
  echo "$(date +"%Y-%m-%d %H:%M:%S") INFO $root_dir detected"
fi
sca_ver=$(scala -version 2>&1)
if [[ $sca_ver == *"2.12.17"* ]];then
  echo "$(date +"%Y-%m-%d %H:%M:%S") INFO scala 2.12.17 detected"
  exit 0
else
  if [[ $sca_ver == *"not found"* ]];then
    echo "$(date +"%Y-%m-%d %H:%M:%S") WARNING scala is not found,installing..."
  else
    echo "$(date +"%Y-%m-%d %H:%M:%S") ERROR other version of scala (2.12.17 is required),uninstall it first"
    exit 1
  fi
fi

if [ ! -d "$root_dir/scala" ];then
  echo "$(date +"%Y-%m-%d %H:%M:%S") INFO $root_dir/scala undetected"
  tar -xvf scala-2.12.17.tgz
  mv scala-2.12.17 $root_dir/scala
else
  echo "$(date +"%Y-%m-%d %H:%M:%S") WARNING $root_dir/scala detected"
fi

if [[ -z "$SCALA_HOME" ]];then
  echo "export SCALA_HOME=$root_dir/scala" >> ~/.bashrc
  echo 'export PATH=$SCALA_HOME/bin:$PATH' >> ~/.bashrc
  echo "export SCALA_HOME=$root_dir/scala" >> /etc/profile
  echo 'export PATH=$SCALA_HOME/bin:$PATH' >> /etc/profile
  source ~/.bashrc
  source /etc/profile
else
  echo "$(date +"%Y-%m-%d %H:%M:%S") INFO SCALA_HOME is set"
fi
scala -version
if [ $? -eq 0 ];then
  echo "$(date +"%Y-%m-%d %H:%M:%S") INFO installing scala success"
else
  echo "$(date +"%Y-%m-%d %H:%M:%S") ERROR installing scala fail"
fi